<?php
namespace yan\googlebusiness;
abstract class AbstractService{
    private static $_instances = [];
    private $services;
    
    protected static $classMap = [
    ];

    public function __construct()
    {
        $this->services = [];
    }
    public static function instance($refresh = false){
        $className = get_called_class();
        if($refresh || empty(self::$_instances[$className])){            
            self::$_instances[$className] = new $className;
        }
        return self::$_instances[$className];
    }

    protected function getServiceClass($name)
    {
        return \array_key_exists($name, static::$classMap) ? static::$classMap[$name] : null;
    }

    public function __get($name)
    {
        $serviceClass = $this->getServiceClass($name);
        
        if (null !== $serviceClass) {
            if (!\array_key_exists($name, $this->services)) {
                if(is_array($serviceClass)){
                    if(isset($serviceClass['class'])){
                        $this->services[$name] = $serviceClass['client'] ? $serviceClass['class']::instance($this) : $serviceClass['class']::instance() ;
                    }
                }else{
                    $this->services[$name] = $serviceClass::instance();
                }
                
            }

            return $this->services[$name];
        }
        // \trigger_error('Undefined property: ' . static::class . '::$' . $name);
        return null;
    }

}